import {
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  RadioButton,
  RadioGroup,
  RangePicker,
  Space,
  TypographyText
} from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'

import cardApi from '@/apis/cardApi'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { formatDate, optionsToMap } from '@/utils'
import { handlePrice } from '@/utils/bsshow'

export default defineComponent({
  name: 'CardGoodsManage',
  setup() {
    const dialogLoading = ref(false)
    const showDialog = ref(false)
    const brandType = ref(5)

    const { showConfirm } = useDialog()

    const tableRef = ref({} as ProTableRef)
    const optionItemCur = ref({} as any)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        columnConfig: {
          minWidth: 100
        },
        columns: [
          {
            title: 'ID',
            field: 'apiId'
          },
          {
            title: '充值类型',
            field: 'rechargeType'
          },
          {
            title: '充值面额',
            field: 'rechargeDenomination'
          },
          {
            title: '第三方价格',
            field: 'totalPrice',
            formatter: ({ cellValue }) => {
              return '￥' + cellValue
            }
          },
          {
            title: '我方价格',
            slots: {
              default: 'salePrice'
            }
          },
          {
            title: '显示样式',
            field: 'viewStyle',
            minWidth: 150
          },
          {
            title: '显示期限',
            minWidth: 250,
            slots: {
              default: 'timeRange'
            }
          },
          {
            title: '状态',
            slots: {
              default: 'status'
            },
            width: 100
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 180
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          props: {
            result: 'data',
            total: 'data.length'
          },
          ajax: {
            query: async () => {
              const data = await cardApi.getGoodsList(brandType.value)
              return { data: data }
            }
          }
        }
      }
    } as ProTableProps)

    //刷新
    async function refresh() {
      await tableRef.value.table.commitProxy('query')
    }

    //编辑
    function handleEdit(row) {
      optionItemCur.value = JSON.parse(JSON.stringify(row))
      optionItemCur.value['priceNow'] = handlePrice(row.ourPrice, row.ourPoints)
      if (row.viewStartTime) {
        optionItemCur.value.timeRange = [
          moment(row.viewStartTime),
          moment(row.viewEndTime)
        ]
      } else {
        optionItemCur.value.timeRange = []
      }
      showDialog.value = true
    }
    //编辑确定
    async function dialogConfirm() {
      dialogLoading.value = true
      if (
        optionItemCur.value.timeRange &&
        optionItemCur.value.timeRange.length > 0
      ) {
        optionItemCur.value.viewStartTime =
          optionItemCur.value.timeRange[0].format('x')
        optionItemCur.value.viewEndTime =
          optionItemCur.value.timeRange[1].format('x')
      }
      try {
        await cardApi.editGoods(optionItemCur.value)
        refresh()
        showDialog.value = false
      } finally {
        dialogLoading.value = false
      }
    }

    //上下架
    function handleDownUp(row) {
      showConfirm({
        content: `请确认是否${row.productStatus == 0 ? '上架' : '下架'}该商品?`,
        onOk: async () => {
          try {
            await cardApi.upDownGoods(row.apiId, row.productStatus == 0 ? 1 : 0)
            refresh()
            message.success('操作完成')
          } catch (error) {}
        }
      })
    }

    return {
      tableRef,
      tableConfig,
      brandType,
      dialogLoading,
      showDialog,
      optionItemCur,

      dialogConfirm,
      handleDownUp,
      refresh,
      handleEdit
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbarButtons: () => (
              <RadioGroup
                v-model={[this.brandType, 'value']}
                onChange={this.refresh}
              >
                <RadioButton value={5}>腾讯视频</RadioButton>
                <RadioButton value={6}>爱奇艺</RadioButton>
                <RadioButton value={7}>芒果TV</RadioButton>
                <RadioButton value={8}>优酷视频</RadioButton>
              </RadioGroup>
            ),
            timeRange: ({ row }) => (
              <Space>
                <span>
                  {row.viewStartTime
                    ? `${formatDate(row.viewStartTime)} 至 ${formatDate(
                        row.viewEndTime
                      )}`
                    : '无'}
                </span>
              </Space>
            ),
            salePrice: ({ row }) => {
              return <Space>{handlePrice(row.ourPrice, row.ourPoints)}</Space>
            },
            status: ({ row }) => {
              return (
                <Space>
                  {row.productStatus == 0 ? (
                    <TypographyText type="danger">下架</TypographyText>
                  ) : (
                    <TypographyText type="success">上架</TypographyText>
                  )}
                </Space>
              )
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDownUp(row)}
                >
                  {row.productStatus === 0 ? '上架' : '下架'}
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showDialog}
          confirmLoading={this.dialogLoading}
          title={'编辑'}
          onOk={this.dialogConfirm}
        >
          <Form labelCol={{ span: 4 }}>
            <FormItem>
              <p>{'当前价格：' + this.optionItemCur['priceNow']}</p>
            </FormItem>
            <FormItem label={'价格'}>
              <InputNumber
                v-model:value={this.optionItemCur.ourPrice}
                placeholder="请输入"
                min={0}
                max={1000}
                precision={2}
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label={'金豆'}>
              <InputNumber
                v-model:value={this.optionItemCur.ourPoints}
                placeholder="请输入"
                min={0}
                max={1000}
                precision={2}
                style={{ width: '300px' }}
              />
            </FormItem>
          </Form>

          <FormItem label={'显示样式：'}>
            <Input
              placeholder={'请输入'}
              v-model:value={this.optionItemCur.viewStyle}
              style={{ width: '400px' }}
              maxlength={8}
              v-slots={{
                suffix: () => (
                  <span>{this.optionItemCur.viewStyle?.length || 0}/8</span>
                )
              }}
            />
          </FormItem>
          <FormItem label={'显示期限：'}>
            <Space>
              <RangePicker
                v-model:value={this.optionItemCur.timeRange}
                showTime={{
                  hideDisabledOptions: true,
                  defaultValue: [
                    moment('00:00:00', 'HH:mm:ss'),
                    moment('23:59:59', 'HH:mm:ss')
                  ]
                }}
                format={'YYYY-MM-DD HH:mm:ss'}
                separator={'至'}
                style={{ width: '400px' }}
              />
            </Space>
          </FormItem>
        </Modal>
      </div>
    )
  }
})
